﻿using System;
using System.Collections.Generic;
using System.Text;

using Gx.Model.Entity;//实体
using Gx.Common;//通用类
using Gx.Model;
using Gx.Dal.Employee;
using Gx.Model.Enums;
using System.Linq;
using Gx.Bll.Shared;

namespace Gx.Bll.Employee
{
    /// <summary>
    /// 采购单
    /// </summary>
    public class G_PurchaseOrderInfoBll
    {
        public ReturnModel<bool> AddG_PurchaseOrderInfo(string data)
        {
            using (G_PurchaseOrderInfoDal dal = new G_PurchaseOrderInfoDal())
            {
                ReturnModel<bool> r = new ReturnModel<bool>()
                {
                    Code = (int)Code.操作失败,
                    Msg = "操作失败",
                    Success = false,
                };
                if (string.IsNullOrEmpty(data))
                {
                    r.Msg = "参数错误";
                    return r;
                }
                G_PurchaseOrderInfo model = JsonHelper.DeserializeObject<G_PurchaseOrderInfo>(data);
                if (model.GoodsList == null && model.GoodsList.Count == 0)
                {
                    r.Msg = "请选择物料";
                    return r;
                }
                if (model.GoodsList.Exists(x => x.NeedNum <= 0))
                {
                    r.Msg = "采购数量必须都大于0";
                    return r;
                }
                if (model.GoodsList.Exists(x => x.TotalPrice <= 0))
                {
                    r.Msg = "采购总价需要大于0";
                    return r;
                }
                if (model.CheckUser < 0)
                {
                    r.Msg = "请选择复核人";
                    return r;
                }
                if (model.GoodsList.GroupBy(x => x.GoodsId).Any(x => x.Count() > 1))
                {
                    r.Msg = "物料不能重复";
                    return r;
                }
                List<int> goodsIdList = model.GoodsList.Select(x => x.GoodsId).Distinct().ToList();
                List<G_GoodsInfo> goodsList = new G_GoodsInfoBll().GetG_GoodsInfoList(goodsIdList);

                model.AddTime = model.LastEditTime = DateTime.Now;
                model.EmployeeId = model.AddUser = model.LastEditUser = LoginHelper.GetUserId();
                model.CheckStatus = (int)CheckStatus.审批中;
                model.BillStatus = (int)BillStatus.正常;
                model.BillNo = DateTime.Now.ToStringyyyyMMddHHmmfff("CG");
                model.GoodsId = goodsIdList.Join();
                model.GoodsName = string.Join(",", goodsList.Select(x => x.GoodsName));

                model.GoodsList.ForEach(x =>
                {
                    model.TotalPrice += x.TotalPrice;
                    x.AddTime = x.LastEditTime = model.AddTime;
                    x.AddUser = x.LastEditUser = model.AddUser;
                });
                int PurchaseOrderId = dal.AddG_PurchaseOrderInfo(model);
                if (PurchaseOrderId == 0)
                {
                    r.Code = (int)Code.服务端错误;
                    r.Msg = "服务端错误";
                    return r;
                }
                new M_LogInfoBll().AddOptionsLog("AddG_PurchaseOrderInfo", "添加一条采购单信息", data);
                G_PurchaseOrderGoodsInfoBll goodsBll = new G_PurchaseOrderGoodsInfoBll();
                foreach (var item in model.GoodsList)
                {
                    item.PurchaseOrderId = PurchaseOrderId;
                    item.UnitValue = goodsList.Exists(x => x.GoodsId == item.GoodsId) ? goodsList.Find(x => x.GoodsId == item.GoodsId).UnitValue : 0;
                    goodsBll.AddG_PurchaseOrderGoodsInfo(item);
                }
                r.Code = (int)Code.操作成功;
                r.Msg = "操作成功";
                r.Data = true;
                r.Success = true;

                return r;
            }
        }

        //public ReturnModel<bool> AddG_PurchaseOrderInfo(string json)
        //{
        //    using (G_PurchaseOrderInfoDal dal = new G_PurchaseOrderInfoDal())
        //    {
        //        ReturnModel<bool> r = new ReturnModel<bool>()
        //        {
        //            Code = (int)Code.操作失败,
        //            Msg = "操作失败",
        //            Success = false,
        //        };
        //        G_PurchaseOrderInfo model = JsonHelper.DeserializeObject<G_PurchaseOrderInfo>(json);
        //        if (model.GoodsId.IsNullOrEmpty() || model.GoodsList == null)
        //        {
        //            r.Msg = "请选择物料";
        //            return r;
        //        }

        //        if (model. < 0)
        //        {
        //            r.Msg = "采购数量必须大于0";
        //            return r;
        //        }
        //        if (model.TotalPrice < 0)
        //        {
        //            r.Msg = "采购总价必须大于0";
        //            return r;
        //        }
        //        if (model.EmployeeId < 0)
        //        {
        //            r.Msg = "请选择采购人";
        //            return r;
        //        }
        //        model.AddTime = model.LastEditTime = DateTime.Now;
        //        model.AddUser = model.LastEditUser = LoginHelper.GetUserId();
        //        model.CheckStatus = (int)CheckStatus.审批中;
        //        model.BillNo = DateTime.Now.ToStringyyyyMMddHHmmfff("RK");
        //        model.GoodsList.ForEach(x =>
        //        {
        //            model.TotalPrice += x.TotalPrice;
        //            x.AddTime = x.LastEditTime = model.AddTime;
        //            x.AddUser = x.LastEditUser = model.AddUser;
        //        });
        //        if (model.PriceList != null)
        //        {
        //            model.PriceList.ForEach(x =>
        //            {
        //                model.AccountPaid += x.Price;
        //                x.AddTime = x.LastEditTime = model.AddTime;
        //                x.AddUser = x.LastEditUser = model.AddUser;
        //            });
        //        }
        //        string res = dal.AddG_PurchaseOrderInfo(model);
        //        if (res != "")
        //        {
        //            r.Code = (int)Code.服务端错误;
        //            r.Msg = res;
        //            return r;
        //        }
        //        new M_LogInfoBll().AddOptionsLog("AddG_PurchaseOrderInfo", "添加一条入库信息", model);
        //        r.Code = (int)Code.操作成功;
        //        r.Msg = "操作成功";
        //        r.Data = true;
        //        r.Success = true;
        //        return r;
        //    }
        //}

        /// <summary>
        ///作废一条入库信息
        /// </summary>
        /// <param name="purchaseOrderId"></param>
        /// <returns></returns>
        public ReturnModel<bool> DelG_PurchaseOrderInfo_BillStatus(int purchaseOrderId)
        {
            using (G_PurchaseOrderInfoDal dal = new G_PurchaseOrderInfoDal())
            {
                ReturnModel<bool> r = new ReturnModel<bool>()
                {
                    Code = (int)Code.操作失败,
                    Msg = "操作失败",
                    Success = false,
                };
                G_PurchaseOrderInfo model = new G_PurchaseOrderInfo
                {
                    LastEditTime = DateTime.Now,
                    LastEditUser = LoginHelper.GetUserId(),
                    BillStatus = (int)BillStatus.作废,
                    PurchaseOrderId = purchaseOrderId,
                };
                bool res = dal.DelG_PurchaseOrderInfo_BillStatus(model);
                if (res)
                {
                    new M_LogInfoBll().AddOptionsLog("DelG_PurchaseOrderInfo_BillStatus", "作废一条采购单信息", model);
                    r.Code = (int)Code.操作成功;
                    r.Msg = "操作成功";
                    r.Data = true;
                    r.Success = true;
                }
                return r;
            }
        }

        public ReturnModel<bool> EditG_PurchaseOrderInfo(G_PurchaseOrderInfo model)
        {
            using (G_PurchaseOrderInfoDal dal = new G_PurchaseOrderInfoDal())
            {
                ReturnModel<bool> r = new ReturnModel<bool>()
                {
                    Code = (int)Code.操作失败,
                    Msg = "操作失败",
                    Success = false,
                };
                //if (model.GoodsId < 1)
                //{
                //    r.Msg = "请选择物料";
                //    return r;
                //}
                //if (model.Num < 0)
                //{
                //    r.Msg = "采购数量必须大于0";
                //    return r;
                //}
                if (model.TotalPrice < 0)
                {
                    r.Msg = "采购总价必须大于0";
                    return r;
                }
                if (model.EmployeeId < 0)
                {
                    r.Msg = "请选择采购人";
                    return r;
                }
                model.LastEditTime = DateTime.Now;
                model.LastEditUser = LoginHelper.GetUserId();
                bool res = dal.EditG_PurchaseOrderInfo(model);
                if (res)
                {
                    new M_LogInfoBll().AddOptionsLog("EditG_PurchaseOrderInfo", "编辑一条采购单信息", model);
                    r.Code = (int)Code.操作成功;
                    r.Msg = "操作成功";
                    r.Data = true;
                    r.Success = true;
                }
                return r;
            }
        }

        public ReturnModel<bool> EditG_PurchaseOrderInfo_CheckUser(G_PurchaseOrderInfo model)
        {
            using (G_PurchaseOrderInfoDal dal = new G_PurchaseOrderInfoDal())
            {
                ReturnModel<bool> r = new ReturnModel<bool>()
                {
                    Code = (int)Code.操作失败,
                    Msg = "操作失败",
                    Success = false,
                };
                model.CheckUser = model.LastEditUser = LoginHelper.GetUserId();
                model.CheckDate = model.LastEditTime = DateTime.Now;
                bool res = dal.EditG_PurchaseOrderInfo_CheckUser(model);
                if (res)
                {
                    new M_LogInfoBll().AddOptionsLog("EditG_PurchaseOrderInfo_CheckUser", "审核一条采购单", model);
                    r.Code = (int)Code.操作成功;
                    r.Msg = "操作成功";
                    r.Data = true;
                    r.Success = true;
                }
                return r;
            }
        }

        private List<G_PurchaseOrderInfo> GetG_PurchaseOrderInfoList(string strWhere)
        {
            using (G_PurchaseOrderInfoDal dal = new G_PurchaseOrderInfoDal())
            {
                return dal.GetG_PurchaseOrderInfoList(strWhere);
            }
        }

        public List<G_PurchaseOrderInfo> GetG_PurchaseOrderInfoList(string BillNo, int? CheckStatus, DateTime? StartCheckDate, DateTime? EndCheckDate, int? BillStatus,
int pageIndex, int pageSize, out int totalCount)
        {
            using (G_PurchaseOrderInfoDal dal = new G_PurchaseOrderInfoDal())
            {
                int PageIndex = (pageIndex - 1) * pageSize + 1;
                int PageSize = pageIndex * pageSize;
                StringBuilder strWhere = new StringBuilder();
                if (!BillStatus.IsNull() && BillStatus > -1)
                {
                    strWhere.AppendFormat("   AND BillStatus={0}", BillStatus);
                }
                if (!CheckStatus.IsNull() && CheckStatus > -1)
                {
                    strWhere.AppendFormat("   AND CheckStatus={0}", CheckStatus);
                }
                if (!BillNo.IsNullOrEmpty())
                {
                    strWhere.AppendFormat(" AND BillNo LIKE '%{0}%'", BillNo);
                }
                if (StartCheckDate.IsDate())
                {
                    strWhere.AppendFormat(" AND CheckDate>='{0}'", StartCheckDate);
                }
                if (EndCheckDate.IsDate())
                {
                    strWhere.AppendFormat(" AND CheckDate <= '{0}' ", EndCheckDate.Value.AddDays(1));
                }
                List<G_PurchaseOrderInfo> list = dal.GetG_PurchaseOrderInfoList(strWhere.ToString(), PageIndex, PageSize, out totalCount);
                foreach (var item in list)
                {
                    item.StrIsStockIn = item.IsStockIn ? "是" : "否";
                    item.StrAccountPaid = item.AccountPaid.ToStringf2();
                    item.StrTotalPrice = item.TotalPrice.ToStringf2();
                    item.StrBillStatus = EnumHelper.GetDataTypeDescription<BillStatus>(item.BillStatus);
                    item.StrCheckStatus = EnumHelper.GetDataTypeDescription<CheckStatus>(item.CheckStatus);
                }
                return list;
            }
        }

        private int GetG_PurchaseOrderInfoCount(string strWhere)
        {
            using (G_PurchaseOrderInfoDal dal = new G_PurchaseOrderInfoDal())
            {
                return dal.GetG_PurchaseOrderInfoCount(strWhere);
            }
        }

        public G_PurchaseOrderInfo GetG_PurchaseOrderInfoModel(int purchaseOrderId, bool isGetEmployee = false)
        {
            using (G_PurchaseOrderInfoDal dal = new G_PurchaseOrderInfoDal())
            {
                G_PurchaseOrderInfo po = dal.GetG_PurchaseOrderInfoModel(purchaseOrderId);
                if (isGetEmployee)
                {
                    List<int> empIdList = new List<int>() { po.CheckUser, po.EmployeeId };
                    List<E_EmployeeInfo> empList = new E_EmployeeInfoBll().GetE_EmployeeInfoList(empIdList);
                    po.EmpName = empList.Exists(x => x.EmployeeId == po.EmployeeId) ? empList.Find(x => x.EmployeeId == po.EmployeeId).EmpName : "员工不存在或已离职";
                    po.CheckUserName = empList.Exists(x => x.EmployeeId == po.CheckUser) ? empList.Find(x => x.EmployeeId == po.CheckUser).EmpName : "员工不存在或已离职";
                }
                return po;
            }
        }



        public bool EditG_PurchaseOrderInfo_BillStatus(G_PurchaseOrderInfo model)
        {
            using (G_PurchaseOrderInfoDal dal = new G_PurchaseOrderInfoDal())
            {
                model.LastEditTime = DateTime.Now;
                model.LastEditUser = LoginHelper.GetUserId();
                return dal.EditG_PurchaseOrderInfo_BillStatus(model);
            }
        }

        public List<G_PurchaseOrderInfo> GetG_PurchaseOrderInfoLikeFront10(string billNo)
        {
            if (billNo.IsNullOrEmpty() || billNo.Length < 2)
            {
                return new List<G_PurchaseOrderInfo>();
            }
            using (G_PurchaseOrderInfoDal dal = new G_PurchaseOrderInfoDal())
            {
                return dal.GetG_PurchaseOrderInfoLikeFront10(billNo);
            }
        }
    }
}
